package cn.itsource.service.impl;

import cn.itsource.constants.Constants;
import cn.itsource.constants.GlobalExceptionCode;
import cn.itsource.feign.LoginApi;
import cn.itsource.pojo.domain.Driver;
import cn.itsource.mapper.DriverMapper;
import cn.itsource.pojo.dto.LoginDto;
import cn.itsource.pojo.dto.WeChatRegisterDto;
import cn.itsource.pojo.properties.WeChatProperties;
import cn.itsource.result.R;
import cn.itsource.service.*;
import cn.itsource.template.WechatTemplate;
import cn.itsource.utils.AssertUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * <p>
 * 司机对象 服务实现类
 * </p>
 *
 * @author 飞越人生
 * @since 2023-12-16
 */
@Service
public class DriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements IDriverService {
    /**
     * 微信注册
     *
     * @param weChatRegisterDto
     * 1.参数校验
     * 2.业务校验
     */


//    @Value("${fycar.wechat.url.open-id-url-template}")
//    private String openIdUrlTemplate;
//
//    @Value("${fycar.wechat.url.access-token-url-template}")
//    private String accessTokenUrlTemplate;
//
//    @Value("${fycar.wechat.url.code-to-phone-url-template}")
//    private String codeToPhoneUrlTemplate;

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private IDriverSettingService driverSettingService;

    @Autowired
    private IDriverSummaryService driverSummaryService;

    @Autowired
    private IDriverWalletService driverWalletService;

    @Autowired
    private LoginApi loginApi;

    @Autowired
    private WechatTemplate wechatTemplate;

    @Override
    public void wechatRegister(WeChatRegisterDto weChatRegisterDto) {

//        //获取到openid https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
//        String url = String.format(openIdUrlTemplate, weChatProperties.getAppId(), weChatProperties.getSecret(), weChatRegisterDto.getOpenIdCode());
//        String resultJson = HttpUtil.get(url);
//        //判断校验为false 如果为true就抛出这个异常
//        AssertUtil.isFalse(resultJson.contains("errCode"), GlobalExceptionCode.WECHAT_REGISTER_ERROR);
//        OpenIdResultDto openIdResultDto = JSONObject.parseObject(resultJson, OpenIdResultDto.class); //转为JSON字符串
//        String openid = openIdResultDto.getOpenid(); //拿到openid



        //2.1判断此用户是否注册
        //Driver::getOpenId: 我要以openid作为条件
        //new LambdaQueryWrapper<Driver>():条件构造器对象
        //eq :等于
        String openId = wechatTemplate.codeToOpenId(weChatRegisterDto.getOpenIdCode());
        Driver driver = super.getOne(new LambdaQueryWrapper<Driver>().eq(Driver::getOpenId, openId));
        AssertUtil.isNull(driver, GlobalExceptionCode.PARAM_PHONE_EXIST);

        //3.业务实现
        //拿到手机号的需要传一个code 获取用户手机号
//        String phone =wechatTemplate.codeToPhone(weChatRegisterDto.getPhoneCode());


        //手机号写死
        String phone = "13242741111";

        //3.1保存司机表
        Long id = saveDriver(openId,phone);

        //3.2初始化司机配置表
        driverSettingService.initDriverSetting(id);

        //3.3初始化司机统计表

        driverSummaryService.initDriverSummary(id);

        //3.4初始化司机钱包表
        driverWalletService.initDriverWallet(id);

        //3.5保存登录表
        LoginDto loginDto = new LoginDto();
        loginDto.setId(id);
        loginDto.setType(Constants.Login.TYPE_DRIVER );
        loginDto.setOpenId(openId);
        loginDto.setPhone(phone);
        R result = loginApi.saveLogin(loginDto);

        AssertUtil.isTrue(result.isSuccess(),GlobalExceptionCode.WECHAT_REGISTER_ERROR);



    }

//    /**
//     * 这是根据phoneCode拿到手机号
//     * @param phoneCode
//     * @return
//     */
//    private String getPhoneNumber(String phoneCode) {
//        //先要获取到access_token
//        //拼接好地址
//        String url = String.format(accessTokenUrlTemplate, weChatProperties.getAppId(), weChatProperties.getSecret());
//        String resultJsonStr = HttpUtil.get(url);
//        //这个里面有errcode就抛出一个系统异常
//        AssertUtil.isFalse(resultJsonStr.contains("errCode"), GlobalExceptionCode.WECHAT_REGISTER_ERROR);
//        //企业在接收参数的时候 有三种方法: 1.封装成dto对象接收参数  2.封装成map  3.封装成JSONObject:这个也是一个key:value结构的
//        JSONObject jsonObject = JSONObject.parseObject(resultJsonStr);
//        String accessToken = jsonObject.getString("access_token");
//
//        //再根据access_token + phoneCode 拿到手机号
//        String phoneUrl = String.format(codeToPhoneUrlTemplate, accessToken);
//        JSONObject param = new JSONObject();
//        param.put("code",phoneCode);
//
//        String phoneResultJsonStr = HttpUtil.post(phoneUrl, JSONObject.toJSONString(param));
//
//        //判断有没有问题 没有问题再转换成JSONobj对象
//        AssertUtil.isFalse(phoneResultJsonStr.contains("errCode"), GlobalExceptionCode.WECHAT_REGISTER_ERROR);
//
//        //phoneResultJsonStr 转换为Json对象
//        JSONObject phoneResultJsonObj = JSONObject.parseObject(phoneResultJsonStr);
//
//        //phoneResultJsonObj 拿到这个phone_info对象
//        String phoneInfo = phoneResultJsonObj.getString("phone_info");
//        //phoneInfo转为JSONobj对象
//        JSONObject phoneInfoJsonObj = JSONObject.parseObject(phoneInfo);
//        //最后拿到手机号码
//        String phoneNumber = phoneInfoJsonObj.getString("phoneNumber");
//
//
//        return phoneNumber;
//    }

    /**
     * 保存司机信息
     *
     * @param openid
     */
    private Long saveDriver(String openid,String phone) {

        Driver driver = new Driver();
        driver.setPhone(phone);
        driver.setCreateTime(new Date());
        driver.setOpenId(openid);
        driver.setBitState(0L);
        //MyBatis的新增方法会把生成的主键返回给你传递给他的对象的id字段
        super.save(driver);
        return driver.getId();
    }
}
